<template>
  <div class="app-container">
    <!-- 客户信息维护 -->
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="客户编号" prop="code">
          <el-select-v2
            v-model="queryParams.code"
            filterable
            clearable
            :options="allCompanyCode"
            value-key="value"
            placeholder="请输入客户编号"
            class="!w-[192px]"
            @change="handleQuery()"
          />
        </el-form-item>

        <el-form-item label="客户名称" prop="companyName">
          <el-input
            v-noSpace
            v-model="queryParams.companyName"
            placeholder="请输入客户名称"
            class="!w-[192px]"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            class="!w-[192px]"
            filterable
            clearable
            @change="handleQuery"
          >
            <el-option
              v-for="item in companyStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="业务员" prop="salesMan">
          <!-- <el-select v-model="queryParams.salesMan" placeholder="请选择业务员" style="width: 250px" filterable clearable
            @change="handleQuery">
            <el-option v-for="item in salesPersonList" :key="item.value" :label="item.label" :value="item.value" /> -->
          <!-- </el-select> -->
          <el-select
            v-model="queryParams.salesMan"
            filterable
            clearable
            placeholder="请输入业务员"
            class="!w-[192px]"
            @change="handleQuery()"
          >
            <el-option
              v-for="item in salesPersonList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="录入日期" prop="inputTime">
          <el-date-picker
            v-model="queryParams.inputTime"
            type="daterange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleQuery()"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
          <el-button
            type="warning"
            icon="menu"
            @click="handleOpenDialog"
            v-hasPerm="'sys:cusInfo:edit'"
          >
            新增
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 客户列表 -->
    <el-card shadow="never">
      <el-table v-loading="loading" :data="pageData" :show-overflow-tooltip="true">
        <el-table-column prop="code" label="客户编号" width="180" align="center" />
        <el-table-column prop="companyName" label="中文名称" width="180" align="center" />
        <el-table-column prop="nickName" label="简称" width="180" align="center" />
        <el-table-column prop="clientType" label="客户类型" width="180" align="center">
          <template #default="scope">
            {{ customerTypeLabel(scope.row.clientType) }}
          </template>
        </el-table-column>
        <el-table-column prop="businessLicenseNo" label="营业执照号码" width="180" align="center" />
        <el-table-column
          prop="registerAddress"
          label="客户注册地址"
          width="180"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column prop="creditLimit" label="授信额度" width="120" align="center">
          <template #default="scope">
            {{ scope.row.creditLimit || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="客户状态" width="180" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.status == 1" type="warning">风险客户</el-tag>
            <el-tag v-if="scope.row.status == 2" type="danger">失信客户</el-tag>
            <el-tag v-if="scope.row.status == 0" type="success">正常客户</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="salesMan" label="业务员" width="180" align="center">
          <template #default="scope">
            {{
              salesPersonList.filter((item) => item.value.toString() == scope.row.salesMan)[0]
                ?.label
            }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="录入时间" width="180" align="center" />

        <el-table-column label="操作" width="300px" fixed="right" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              v-hasPerm="'sys:cusInfo:money'"
              link
              size="small"
              @click="handleOpenCreditDialog(scope.row)"
            >
              授信
            </el-button>
            <el-button
              type="primary"
              link
              size="small"
              @click="handleOpenDialog(scope.row, 'look')"
            >
              查看
            </el-button>
            <el-button
              type="primary"
              v-hasPerm="'sys:cusInfo:fol'"
              link
              size="small"
              @click="handleOpenFollowDialog(scope.row)"
            >
              跟进
            </el-button>
            <el-button
              type="primary"
              link
              size="small"
              @click="handleOpenFollowViewDialog(scope.row)"
            >
              跟进查看
            </el-button>
            <el-button
              type="warning"
              link
              size="small"
              v-hasPerm="'sys:cusInfo:edit'"
              @click="handleOpenDialog(scope.row, 'update')"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              v-hasPerm="'sys:cusInfo:del'"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 查看，新增 -->
    <el-dialog
      v-model="infoDialog.visible"
      :title="infoDialog.title"
      width="800px"
      @close="handleCloseDialog"
    >
      <el-tabs v-model="activeTabsName" class="demo-tabs" @tab-click="handleTabsClick">
        <el-tab-pane label="基础信息" name="基础信息">
          <el-form
            ref="infoFormRef"
            :model="infoFormData"
            label-width="100px"
            :disabled="infoDialog.type == 'look' || submitButtonDisabled == true"
            :rules="infoRules"
          >
            <el-row mt-8>
              <!-- <el-col :span="12">
                <el-form-item label="客户编号" prop="code" label-width="140px">
                  <el-input v-noSpace v-model="infoFormData.code" placeholder="请输入客户编号" />
                </el-form-item>
              </el-col> -->

              <el-col :span="12">
                <el-form-item label="中文名称" prop="companyName" label-width="140px">
                  <el-input
                    v-noSpace
                    v-model="infoFormData.companyName"
                    placeholder="请输入中文名称"
                    :maxlength="50"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="英文名称" prop="otherName" label-width="140px">
                  <el-input
                    v-noSpace
                    v-model="infoFormData.otherName"
                    placeholder="请输入英文名称"
                    :maxlength="50"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="简称" prop="nickName" label-width="140px">
                  <el-input
                    v-noSpace
                    v-model="infoFormData.nickName"
                    placeholder="请输入简称"
                    :maxlength="15"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="主要联系人" prop="contactPerson" label-width="140px">
                  <el-input
                    v-noSpace
                    v-model="infoFormData.contactPerson"
                    placeholder="请输入主要联系人"
                    :maxlength="30"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="状态" prop="status" label-width="140px">
                  <el-select v-model="infoFormData.status" placeholder="请选择状态">
                    <el-option
                      v-for="item in companyStatus"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="客户类型" prop="clientType" label-width="140px">
                  <el-select v-model="infoFormData.clientType" placeholder="请选择客户类型">
                    <el-option
                      v-for="item in customerTypeList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="营业执照号码" prop="businessLicenseNo" label-width="140px">
                  <el-input
                    v-noSpace
                    v-model="infoFormData.businessLicenseNo"
                    placeholder="请输入营业执照号码"
                    :maxlength="18"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="客户注册地址" prop="registerAddress" label-width="140px">
                  <area-select
                    :model-value="infoFormData.registerAddress"
                    @get-address="handleGetregisterAddress"
                  />
                </el-form-item>
              </el-col>
              <!-- <el-col :span="12">
                <el-form-item label="授信额度" prop="creditLimit" label-width="140px">
                  <el-input v-noSpace
                    v-model="infoFormData.creditLimit"
                    type="number"
                    placeholder="请输入授信额度"
                  />
                </el-form-item>
              </el-col> -->
              <el-col :span="12">
                <el-form-item label="授信截止时间" prop="creditDeadline" label-width="140px">
                  <el-date-picker
                    v-model="infoFormData.creditDeadline"
                    type="date"
                    placeholder="选择日期"
                    style="width: 100%"
                    value-format="YYYY-MM-DD"
                    picker-options="pickerOptions"
                    :disabled-date="disabledDate"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="业务员" prop="salesMan" label-width="140px">
                  <el-select
                    v-model="infoFormData.salesMan"
                    filterable
                    clearable
                    placeholder="请输入业务员"
                  >
                    <el-option
                      v-for="item in salesPersonList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value.toString()"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="公司网站" prop="website" label-width="140px">
                  <el-input
                    v-noSpace
                    v-model="infoFormData.website"
                    placeholder="请输入公司网站"
                    :maxlength="50"
                  >
                    <template #prepend>Http://</template>
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="对应财务系统编号" prop="accCode" label-width="140px">
                  <el-input
                    v-noSpace
                    v-model="infoFormData.accCode"
                    placeholder="请输入对应财务系统编号"
                    :maxlength="20"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="对应财务系统名称" prop="accName" label-width="140px">
                  <el-input
                    v-noSpace
                    v-model="infoFormData.accName"
                    placeholder="请输入对应财务系统名称"
                    :maxlength="30"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="银行信息" prop="bankInfo" label-width="140px">
                  <el-input
                    v-noSpace
                    v-model="infoFormData.bankInfo"
                    type="textarea"
                    placeholder="请输入银行信息"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark" label-width="140px">
                  <el-input
                    v-noSpace
                    v-model="infoFormData.remark"
                    type="textarea"
                    placeholder="请输入备注"
                    maxlength="500"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>

              <el-col :span="18">
                <el-form-item label="附件" prop="fileInfoJson" label-width="140px">
                  <!-- 左侧显示所有附件，右侧有一个上传附件按钮 -->
                  <div v-if="infoFormData.fileInfoJson" style="width: 100%">
                    <el-row
                      v-for="(item, index) in JSON.parse(infoFormData.fileInfoJson)"
                      :key="index"
                    >
                      <el-col :span="12">
                        <el-text type="primary">{{ item.name }}</el-text>
                      </el-col>
                      <el-col :span="12">
                        <el-link type="primary" @click="downloadFile(item.name, item.url)">
                          下载
                        </el-link>
                        <el-link type="danger" @click="deleteFile(index)" class="ml-4">
                          删除
                        </el-link>
                      </el-col>
                    </el-row>
                  </div>
                  <div v-else style="width: 100%">
                    <el-row />
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <FileUpload
                  v-if="infoDialog.type !== 'look'"
                  v-model:model-value="fileInfoJson"
                  uploadBtnText="点击上传"
                  :showTip="true"
                  :data="{ bizType: 'contract' }"
                  :maxSize="5 * 1024 * 1024"
                  :showFileList="false"
                  @update:modelValue="handleUpdateFileInfoJson"
                />
              </el-col>
            </el-row>

            <div v-if="infoDialog.type !== 'look'" class="flex-center">
              <el-button v-debounce="handleSubmitBase" type="primary">提 交</el-button>
            </div>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="地址信息" name="地址信息">
          <el-scrollbar max-height="500px">
            <el-button
              v-if="infoDialog.type !== 'look'"
              type="primary"
              @click="handleOpenAddressDialog"
            >
              新增收货地址
            </el-button>
            <div class="bg-gray-50 p-3">
              <div class="mx-auto max-w-4xl">
                <div class="grid gap-4">
                  <div
                    v-for="(address, index) in addressList"
                    :key="index"
                    class="bg-white rounded-lg shadow-sm p-6 relative"
                  >
                    <!-- 第一行 -->
                    <div class="flex items-center justify-between mb-4">
                      <div class="flex items-center space-x-4">
                        <span class="text-lg font-medium">
                          {{ address.contactPerson }} - {{ address.tel }}
                        </span>
                        <div class="flex gap-2">
                          <span
                            v-if="address.isDefault"
                            class="px-2 py-1 bg-blue-100 text-blue-600 text-xs rounded-md"
                          >
                            默认地址
                          </span>
                          <span
                            v-if="address.isShipping"
                            class="px-2 py-1 bg-green-100 text-green-600 text-xs rounded-md"
                          >
                            送货地址
                          </span>
                          <span
                            v-if="address.isBilling"
                            class="px-2 py-1 bg-purple-100 text-purple-600 text-xs rounded-md"
                          >
                            账单地址
                          </span>
                        </div>
                      </div>
                      <el-button
                        v-if="infoDialog.type !== 'look'"
                        class="text-gray-400 hover:text-gray-600 transition-colors"
                        link
                        @click="deleteAddress(address.id)"
                      >
                        <el-icon>
                          <Close />
                        </el-icon>
                      </el-button>
                    </div>
                    <!-- 第二行 -->
                    <div class="text-gray-600 mb-3">
                      {{ address.address }}
                    </div>
                    <!-- 第三行 -->
                    <!-- <div class="text-gray-600 mb-2">
                      <span class="inline-block w-20 text-gray-400">联系人：</span>
                      {{ address.contactPerson }}
                    </div> -->
                    <!-- 第四行 -->
                    <!-- <div class="text-gray-600 mb-2">
                      <span class="inline-block w-20 text-gray-400">联系电话：</span>
                      {{ address.tel }}
                    </div> -->
                    <!-- 第五行 -->
                    <div class="text-gray-600 mb-2">
                      <span class="inline-block w-20 text-gray-400">电子邮箱：</span>
                      {{ address.email || "-" }}
                    </div>
                    <!-- 第六行 -->
                    <div class="bg-gray-50 pt-2 pb-2 rounded-md mb-4 text-gray-600 text-sm">
                      <span class="text-gray-400">备注：</span>
                      {{ address.remark || "-" }}
                    </div>
                    <!-- 第七行 -->
                    <div v-if="infoDialog.type !== 'look'" class="flex justify-end gap-4">
                      <el-button
                        v-if="!address.isShipping"
                        link
                        type="success"
                        @click="updateAddress('isShipping', address)"
                      >
                        <el-icon>
                          <Location />
                        </el-icon>
                        <span>设为送货地址</span>
                      </el-button>
                      <el-button
                        v-if="!address.isBilling"
                        link
                        type="success"
                        @click="updateAddress('isBilling', address)"
                      >
                        <el-icon>
                          <Wallet />
                        </el-icon>
                        <span>设为账单地址</span>
                      </el-button>
                      <el-button
                        v-if="!address.isDefault"
                        link
                        type="primary"
                        @click="updateAddress('isDefault', address)"
                      >
                        <el-icon>
                          <Star />
                        </el-icon>
                        <span>设为默认地址</span>
                      </el-button>
                      <el-button
                        link
                        type="primary"
                        @click="handleOpenAddressDialog(address, 'edit')"
                      >
                        <el-icon>
                          <Edit />
                        </el-icon>
                        <span>编辑</span>
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-scrollbar>
        </el-tab-pane>
        <el-tab-pane label="联系人信息" name="联系人信息">
          <el-scrollbar max-height="500px">
            <el-button
              v-if="infoDialog.type !== 'look'"
              type="primary"
              @click="handleOpenContactDialog"
            >
              新增联系人
            </el-button>
            <div class="bg-gray-50 p-3">
              <div class="mx-auto max-w-4xl">
                <div class="grid gap-4">
                  <div
                    v-for="(contact, index) in contactList"
                    :key="index"
                    class="bg-white rounded-lg shadow-sm p-6 relative"
                  >
                    <!-- 第一行 -->
                    <div class="flex items-center justify-between mb-4">
                      <div class="flex items-center space-x-4">
                        <span class="text-lg font-medium">{{ contact.contactPerson }}</span>
                        <div class="flex gap-2" v-if="contact.department">
                          <span class="px-2 py-1 bg-blue-100 text-blue-600 text-xs rounded-md">
                            {{ contact.department }}
                          </span>
                        </div>
                      </div>
                      <el-button
                        v-if="infoDialog.type !== 'look'"
                        link
                        class="text-gray-400 hover:text-gray-600 transition-colors"
                        @click="deleteContact(contact.id)"
                      >
                        <el-icon>
                          <Close />
                        </el-icon>
                      </el-button>
                    </div>
                    <!-- 第二行 -->
                    <!-- <div class="text-gray-600 mb-2">
                      <span class="inline-block w-20 text-gray-400">部门：</span>
                      {{ contact.department || "-" }}
                    </div> -->
                    <!-- 第三行 -->
                    <div class="text-gray-600 mb-2">
                      <span class="inline-block w-20 text-gray-400">职位：</span>
                      {{ contact.position || "-" }}
                    </div>
                    <!-- 第四行 -->
                    <div class="text-gray-600 mb-2">
                      <span class="inline-block w-20 text-gray-400">联系电话：</span>
                      {{ contact.tel || "-" }}
                    </div>
                    <!-- 第五行 -->
                    <div class="text-gray-600 mb-2">
                      <span class="inline-block w-20 text-gray-400">电子邮箱：</span>
                      {{ contact.email || "-" }}
                    </div>
                    <!-- 第六行 -->
                    <div class="bg-gray-50 pt-2 pb-2 rounded-md mb-4 text-gray-600 text-sm">
                      <span class="text-gray-400">备注：</span>
                      {{ contact.remark || "-" }}
                    </div>
                    <!-- 第七行 -->
                    <div v-if="infoDialog.type !== 'look'" class="flex justify-end gap-4">
                      <el-button
                        link
                        type="warning"
                        class="flex items-center space-x-2 text-blue-600 hover:text-blue-700 transition-colors !rounded-button whitespace-nowrap"
                        @click="handleOpenContactDialog(contact)"
                      >
                        <el-icon>
                          <Edit />
                        </el-icon>
                        <span>编辑</span>
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-scrollbar>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <!-- 地址弹窗 -->
    <el-dialog
      v-model="addressDialog.visible"
      :title="addressDialog.title"
      width="500px"
      @close="handleCloseAddressDialog"
    >
      <el-form
        ref="addressRef"
        :model="addressParams"
        :disabled="infoDialog.type == 'look'"
        :rules="addressRules"
      >
        <!-- <el-form-item label="地址名" prop="addressName" label-width="80px">
          <el-input v-noSpace v-model="addressParams.addressName" placeholder="请输入地址名" />
        </el-form-item> -->
        <el-form-item label="详细地址" prop="address" label-width="80px">
          <!-- <el-input v-noSpace v-model="addressParams.address" placeholder="请输入详细地址" /> -->
          <area-select :model-value="addressParams.address" @get-address="handleGetAdress" />
        </el-form-item>

        <el-form-item label="联系人" prop="contactPerson" label-width="80px">
          <el-input
            v-noSpace
            v-model="addressParams.contactPerson"
            placeholder="请输入联系人"
            :maxlength="20"
          />
        </el-form-item>

        <el-form-item label="联系电话" prop="tel" label-width="80px">
          <el-input
            v-noSpace
            v-model="addressParams.tel"
            placeholder="请输入联系电话"
            :maxlength="20"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email" label-width="80px">
          <el-input
            v-noSpace
            v-model="addressParams.email"
            placeholder="请输入邮箱"
            :maxlength="20"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark" label-width="80px">
          <el-input
            v-noSpace
            v-model="addressParams.remark"
            type="textarea"
            placeholder="请输入备注"
            :maxlength="120"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="" label-width="80px">
          <el-checkbox
            v-model="addressParams.isDefault"
            label="默认地址"
            :true-value="1"
            :false-value="0"
            size="large"
          />

          <el-checkbox
            v-model="addressParams.isBilling"
            label="账单地址"
            :true-value="1"
            :false-value="0"
            size="large"
          />
          <el-checkbox
            v-model="addressParams.isShipping"
            label="送货地址"
            :true-value="1"
            :false-value="0"
            size="large"
          />
        </el-form-item>
        <div v-if="infoDialog.type !== 'look'" class="dialog-footer flex-center">
          <el-button type="primary" v-debounce="handleSaveAddress">保存地址信息</el-button>
        </div>
      </el-form>
    </el-dialog>
    <!-- 联系人信息弹窗 -->
    <el-dialog
      v-model="contactDialog.visible"
      :title="contactDialog.title"
      @close="handleCloseContactDialog"
    >
      <el-form
        ref="contactRef"
        :model="contactPersonParams"
        :disabled="infoDialog.type == 'look'"
        :rules="contactRules"
      >
        <el-form-item label="联系人" prop="contactPerson" label-width="80px">
          <el-input
            v-noSpace
            v-model="contactPersonParams.contactPerson"
            placeholder="请输入联系人"
            :maxlength="20"
          />
        </el-form-item>

        <el-form-item label="部门" prop="department" label-width="80px">
          <el-input
            v-noSpace
            v-model="contactPersonParams.department"
            placeholder="请输入部门"
            :maxlength="20"
          />
        </el-form-item>
        <el-form-item label="职位" prop="position" label-width="80px">
          <el-input
            v-noSpace
            v-model="contactPersonParams.position"
            placeholder="请输入职位"
            :maxlength="20"
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="tel" label-width="80px">
          <el-input
            v-noSpace
            v-model="contactPersonParams.tel"
            placeholder="请输入联系电话"
            :maxlength="20"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email" label-width="80px">
          <el-input
            v-noSpace
            v-model="contactPersonParams.email"
            placeholder="请输入邮箱"
            :maxlength="20"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark" label-width="80px">
          <el-input
            v-noSpace
            v-model="contactPersonParams.remark"
            type="textarea"
            placeholder="请输入备注"
            :maxlength="120"
            show-word-limit
          />
        </el-form-item>
        <div class="dialog-footer flex-center">
          <el-button v-if="infoDialog.type !== 'look'" type="primary" @click="handleSaveContact()">
            保存联系人信息
          </el-button>
        </div>
      </el-form>
    </el-dialog>
    <!-- 跟进弹窗 -->
    <el-dialog
      v-model="followDialog.visible"
      :title="followDialog.title"
      width="500px"
      @close="handleCloseFollowDialog"
    >
      <el-form ref="followRef" :model="followParams" :rules="followRules">
        <el-form-item label="跟进业务员" prop="followContactPerson" label-width="100px">
          <el-select
            v-model="followParams.followContactPerson"
            filterable
            clearable
            placeholder="请输入业务员"
          >
            <el-option
              v-for="item in salesPersonList"
              :key="item.value"
              :label="item.label"
              :value="item.value.toString()"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactType" label-width="100px">
          <el-input
            v-noSpace
            v-model="followParams.contactType"
            type="tel"
            placeholder="请输入联系电话"
          />
        </el-form-item>
        <el-form-item label="跟进时间" prop="followDate" label-width="100px">
          <el-date-picker
            v-model="followParams.followDate"
            style="width: 100%"
            type="datetime"
            placeholder="选择日期时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :disabled-date="disabledDate"
          />
          <!-- <el-input v-noSpace v-model="followParams.followDate" placeholder="请选择跟进时间" /> -->
        </el-form-item>

        <el-form-item label="跟进记录" prop="remark" label-width="100px">
          <el-input
            v-noSpace
            v-model="followParams.remark"
            type="textarea"
            placeholder="请输入跟进记录"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <div class="dialog-footer flex-center">
          <el-button type="primary" v-debounce="handleSaveFollow">保存跟进记录</el-button>
        </div>
      </el-form>
    </el-dialog>
    <!-- 跟进查看弹窗 -->

    <el-dialog
      v-model="followViewDialog.visible"
      :title="followViewDialog.title"
      width="90%"
      :show-close="true"
      class="max-w-[500px]"
      @close="handleCloseFollowViewDialog"
    >
      <el-scrollbar max-height="400px">
        <div class="space-y-4">
          <div v-if="followList.length == 0" class="bg-white p-4 rounded-lg shadow flex-center">
            <p class="text-gray-600">暂无跟进记录</p>
          </div>
          <div v-else>
            <div
              v-for="(record, index) in followList"
              :key="index"
              class="bg-white p-4 rounded-lg shadow"
            >
              <div class="flex items-center justify-between mb-2">
                <div class="flex items-center">
                  <span class="font-semibold">
                    跟进人：
                    {{
                      salesPersonList.filter(
                        (ele: any) => ele.value == record.followContactPerson
                      )[0]?.label
                    }}
                  </span>
                </div>
                <span class="text-gray-600">跟进时间：{{ record.followDate }}</span>
              </div>

              <p class="text-gray-600 mb-2">跟进记录：</p>
              <p class="text-gray-700 mb-2">{{ record.remark }}</p>
              <div class="flex justify-end">
                <el-button
                  type="danger"
                  size="small"
                  link
                  class="!rounded-button whitespace-nowrap"
                  @click="deleteRecord(record)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </el-dialog>
    <!-- 授信额度弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="授信额度明细"
      width="560px"
      class="credit-dialog"
      @close="handleCloseCreditDialog"
    >
      <div class="credit-info bg-gray-50 rounded-lg p-6 mb-4">
        <div class="flex items-center justify-between">
          <div>
            <div class="text-3xl font-bold text-gray-900">
              ¥ {{ creditAmount?.toFixed(2) || 0 }}
            </div>
            <div class="text-sm text-gray-500 mt-1">当前可用额度</div>
          </div>
          <el-button
            type="primary"
            class="!rounded-button whitespace-nowrap"
            @click="handleRecharge"
            v-hasPerm="'sys:cusInfo:pay'"
          >
            充值
          </el-button>
        </div>
      </div>
      <div class="flex items-center gap-4 mb-4">
        <el-date-picker
          v-model="creditQueryParams.timeScopes"
          type="daterange"
          value-format="YYYY-MM-DD"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="!rounded-button flex-1"
          @change="handleCreditQuery()"
        />
        <!-- <el-select v-model="searchType" placeholder="交易类型" class="w-32 !rounded-button">
          <el-option label="全部" value="" />
          <el-option label="收入" value="income" />
          <el-option label="支出" value="expense" />
        </el-select> -->
        <el-button
          type="primary"
          class="!rounded-button whitespace-nowrap"
          @click="handleCreditQuery()"
        >
          查询
        </el-button>
      </div>
      <el-scrollbar height="400px" class="credit-history">
        <el-empty v-if="historyList?.length === 0" description="暂无记录" />
        <div v-else class="space-y-4">
          <div
            v-for="(item, index) in historyList"
            :key="index"
            class="history-item p-4 border-b border-gray-100"
          >
            <div class="flex items-center justify-between">
              <div class="flex items-center">
                <el-icon
                  class="mr-2"
                  :class="item.creditType % 2 === 0 ? 'text-green-500' : 'text-red-500'"
                >
                  <ArrowUp
                    v-if="
                      item.creditType % 2 === 0 //偶数
                    "
                  />
                  <ArrowDown v-if="item.creditType % 2 !== 0" />
                </el-icon>
                <span class="text-gray-900">{{ creditTypeLabel(item.creditType) }}</span>
              </div>
              <span :class="item.creditType % 2 === 0 ? 'text-green-500' : 'text-red-500'">
                {{ item.creditType % 2 === 0 ? "+" : "-" }} ¥{{
                  item.amount.toString().replaceAll("-", "")
                }}
              </span>
            </div>
            <div class="flex items-center justify-between mt-2">
              <span class="text-sm text-gray-500">{{ item.createTime }}</span>
              <span class="text-sm text-gray-500">{{ item.remark }}</span>
            </div>
          </div>
        </div>
      </el-scrollbar>
      <div class="flex justify-end mt-4">
        <pagination
          v-if="creditTotal > 0"
          v-model:total="creditTotal"
          v-model:page="creditQueryParams.pageNum"
          v-model:limit="creditQueryParams.pageSize"
          @pagination="handleCreditQuery"
        />
      </div>
      <el-dialog
        v-model="rechargeDialogVisible"
        title="充值"
        width="400px"
        append-to-body
        :close-on-click-modal="false"
      >
        <div class="p-4">
          <el-form :model="rechargeForm" label-width="80px">
            <el-form-item label="充值金额">
              <el-input
                v-noSpace
                v-model.number="rechargeForm.amount"
                type="number"
                placeholder="请输入充值金额"
                class="!rounded-button"
              >
                <template #prefix>¥</template>
              </el-input>
            </el-form-item>
            <el-form-item label="备注">
              <el-input
                v-noSpace
                v-model="rechargeForm.remark"
                type="textarea"
                placeholder="请输入备注信息"
                :rows="1"
                maxlength="15"
                show-word-limit
                class="!rounded-button"
              />
            </el-form-item>
          </el-form>

          <div class="flex justify-end mt-6">
            <el-button
              class="!rounded-button whitespace-nowrap mr-4"
              @click="rechargeDialogVisible = false"
            >
              取消
            </el-button>
            <el-button
              type="primary"
              class="!rounded-button whitespace-nowrap"
              @click="handleConfirmRecharge(rechargeForm.companyCode)"
            >
              确认充值
            </el-button>
          </div>
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import cusInfoApi, {
  CompanyContact,
  AddressInfo,
  cusInfoPageQuery,
  cusInfoPageVO,
} from "@/api/cusManage/cusInfo";

import type { FormItemRule, UploadInstance, UploadUserFile } from "element-plus";

import type { TabsPaneContext } from "element-plus";
import salesApi, { FollowUp } from "@/api/sales/sales";
import FileAPI from "@/api/file";
import organizationalAPI from "@/api/basicData/organizational";

import creditAmountRecordApi, {
  creditAmountRecordPageQuery,
  creditAmountRecordPageVO,
} from "@/api/creaditAmount/creaditAmount";
import item from "element-plus/es/components/space/src/item";
import UserAPI from "@/api/system/user";

const disabledDate = (time: Date) => {
  const startDate = new Date();
  startDate.setHours(0, 0, 0, 0); // 设置开始日期为当天的开始时间
  return time.getTime() < startDate.getTime();
};

//客户类型
const customerTypeList = [
  { label: "企业", value: 0 },
  { label: "机关单位", value: 1 },
  { label: "学校", value: 2 },
  { label: "医院", value: 3 },
  { label: "酒店", value: 4 },
  { label: "餐饮门店", value: 5 },
  { label: "中央厨房", value: 6 },
  { label: "团餐", value: 7 },
];

//根据客户类型获取客户类型名称
const customerTypeLabel = (value: number) => {
  return customerTypeList.find((item) => item.value === value)?.label || "未知";
};

//基础信息表单校验
const infoRules: Record<string, FormItemRule[]> = {
  //客户编号
  code: [{ required: true, message: "请输入客户编号", trigger: "blur" }],
  //跟进业务员
  // salesMan: [{ required: true, message: "请选择业务员", trigger: "change" }],
  //中文名称
  companyName: [{ required: true, message: "请输入中文名称", trigger: "blur" }],

  //状态
  status: [{ required: true, message: "请选择状态", trigger: "change" }],

  //英文名称
  otherName: [{ required: true, message: "请输入英文名称", trigger: "blur" }],

  //简称
  nickName: [{ required: true, message: "请输入简称", trigger: "blur" }],
  //主要联系人
  // contactPerson: [{ required: true, message: "请输入主要联系人", trigger: "blur" }],
  //客户类型
  clientType: [{ required: true, message: "请选择客户类型", trigger: "change" }],

  //营业执照号码
  businessLicenseNo: [
    {
      required: true,
      message: "请输入营业执照号码",
      trigger: "blur",
    },
    {
      pattern: /^[A-Z0-9]{18}$/,
      message: "请输入18位数字/大写字母的有效信用代码",
      trigger: "blur",
    },
    // {
    //   validator: (_, value, callback) => {
    //     if (!/^[1-9A-G]/.test(value)) {
    //       callback(new Error("首字符应为1-9或A-G（登记机关代码）"));
    //     } else if (!/[1-9A-NP-RTUW-Y]/.test(value.charAt(1))) {
    //       callback(new Error("第二位应为有效机构类别代码"));
    //     } else {
    //       callback();
    //     }
    //   },
    //   trigger: "blur",
    // },
  ],

  //注册地址
  registerAddress: [{ required: true, message: "请选择注册地址", trigger: "change" }],
  //授信额度
  // creditLimit: [{ required: true, message: "请输入授信额度", trigger: "blur" }],

  //授信截止时间
  creditDeadline: [{ required: true, message: "请选择授信截止时间", trigger: "change" }],
  //公司网站
  website: [
    //网站正则
    {
      pattern: /^[a-zA-Z0-9-]+(\.[a-zA-Z]{2,})+(\/.*)?$/,
      message: "请输入正确格式（如：www.example.com 或 example.com）",
      trigger: "blur",
    },
  ],
  //对应财务系统编号
  accCode: [
    {
      required: true,
      message: "请输入对应财务系统编号",
      trigger: "blur",
    },
  ],
  //对应财务系统名称
  accName: [
    {
      required: true,
      message: "请输入对应财务系统名称",
      trigger: "blur",
    },
  ],
  //银行信息
  bankInfo: [
    {
      required: true,
      message: "请输入银行信息",
      trigger: "blur",
    },
  ],

  //附件
  fileInfoJson: [
    {
      required: true,
      message: "请上传附件",
      trigger: "change",
    },
  ],
};
//获取客户注册地址
const handleGetregisterAddress = (data: {
  code: string[]; //区域码
  name: string[]; //汉字
  isComplete: boolean; //是否选择完整，方便校验
}) => {
  console.log(data, "地址");
  infoFormData.registerAddress = data.name.toString();
};

const handleGetAdress = (data: {
  code: string[]; //区域码
  name: string[]; //汉字
  isComplete: boolean; //是否选择完整，方便校验
}) => {
  console.log(data, "地址");
  addressParams.address = data.name.toString();
};

//地址信息校验
const addressRef = ref();
const addressRules: Record<string, FormItemRule[]> = {
  address: [{ required: true, message: "请选择完整地区信息", trigger: ["change", "blur"] }],
  addressName: [
    {
      required: true,
      message: "请输入地址",
      trigger: "blur",
    },
  ],
  contactPerson: [{ required: true, message: "请输入联系人", trigger: "blur" }],
  tel: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern:
        /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/,
      message: "请输入正确的手机号码",
    },
  ],
  email: [
    // { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] },
  ],
  addressType: [
    {
      required: true,
      message: "请选择地址类型",
      trigger: "change,blur",
    },
  ],
};

//联系人信息校验
const contactRef = ref();
const contactRules: Record<string, FormItemRule[]> = {
  contactPerson: [{ required: true, message: "请输入联系人", trigger: "blur" }],
  // department: [{ required: true, message: "请输入部门", trigger: "blur" }],
  // position: [{ required: true, message: "请输入职位", trigger: "blur" }],
  tel: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern:
        /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/,
      message: "请输入正确的手机号码",
    },
  ],

  email: [
    // { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] },
  ],
};

//客户状态列表
const companyStatus = ref([
  { value: 0, label: "正常客户" },
  { value: 1, label: "风险客户" },
  { value: 2, label: "失信客户" },
]);
//所有客户编号-下拉框

const allCompanyCode = ref<{ code: string; count: number }[]>([]);

//所有业务员-下拉框
const salesPersonList = ref<any[]>([]);

//新增tabs中联系人信息表单
const contactPersonParams = reactive<CompanyContact>({ id: NaN });
//联系人列表
const contactList = ref<CompanyContact[]>([]);

//新增tabs中地址信息表单
const addressParams = reactive<AddressInfo>({ id: NaN });
//地址列表
const addressList = ref<AddressInfo[]>([]);

//跟进弹窗表单
const followParams = reactive<FollowUp>({ id: NaN });
//跟进记录列表
const followList = ref<FollowUp[]>([]);

const queryFormRef = ref(ElForm);
const queryParams = reactive<cusInfoPageQuery>({
  pageNum: 1,
  pageSize: 10,
});
//录入日期日期框可选日期
const shortcuts = [
  {
    text: "过去一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 7);
      return [start, end];
    },
  },
  {
    text: "过去一个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 1);
      return [start, end];
    },
  },
  {
    text: "过去三个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 3);
      return [start, end];
    },
  },
];

const pageData = ref<cusInfoPageVO[]>();

const total = ref(0);

//弹窗配置
//新增弹窗
const infoDialog = reactive({
  title: "",
  visible: false,
  type: "",
});
//跟进弹窗
const followRef = ref();

const followRules = reactive<Record<string, FormItemRule[]>>({
  followContactPerson: [
    {
      required: true,
      message: "请输入业务员",
      trigger: "blur",
    },
  ],
  contactType: [
    {
      required: true,
      message: "请输入联系电话",
      trigger: "blur",
    },
    {
      pattern:
        /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/,
      message: "请输入正确的联系电话",
    },
  ],
  followDate: [
    {
      required: true,
      message: "请选择跟进日期",
      trigger: ["change", "blur"],
    },
  ],
  remark: [
    //最大500
    { min: 0, max: 500, message: "备注长度在 0 到 500 个字符", trigger: "blur" },
  ],
});

const followDialog = reactive({
  title: "",
  visible: false,
});

//跟进查看弹窗
const followViewDialog = reactive({
  title: "",
  visible: false,
});

//Tabs
const activeTabsName = ref("基础信息");
const handleTabsClick = (tab: TabsPaneContext, event: Event) => {
  if (tab.paneName === "基础信息") {
  } else if (tab.paneName === "地址信息") {
  } else if (tab.paneName === "联系人信息") {
  }
};

//基础信息提交表单
const infoFormRef = ref(ElForm);

const loading = ref(false);

//地址弹窗
const addressDialog = reactive({
  title: "",
  visible: false,
  type: "",
});
// 联系人弹窗
const contactDialog = reactive({
  title: "",
  visible: false,
  type: "",
});

const infoFormData = reactive<cusInfoPageVO>({
  salesMan: "", // 跟进业务员
  companyName: "", // 中文名称
  otherName: "", // 英文名称
  nickName: "", // 简称
  contactPerson: "", // 主要联系人
  status: undefined, // 状态
  creditDeadline: "", // 授信截止时间
  website: "", // 公司网站
  accCode: "", // 对应财务系统编号
  accName: "", // 对应财务系统名称
  bankInfo: "", // 银行信息
  remark: "", // 备注
  fileInfoJson: "", // 附件信息，初始化为空数组
});

const fileInfoJson = ref<UploadUserFile[]>([]);

// 查询
function handleQuery() {
  loading.value = true;

  const query = { ...queryParams };

  if (queryParams.inputTime && queryParams.inputTime.length === 2) {
    query.startTime = queryParams.inputTime[0];
    query.endTime = queryParams.inputTime[1];
    delete query.inputTime;
  } else {
    query.startTime = undefined;
    query.endTime = undefined;
    delete query.inputTime;
  }
  cusInfoApi
    .getPage(query)
    .then((data: any) => {
      pageData.value = [...(data.records as cusInfoPageVO[])];

      total.value = data.total;
    })
    .catch((err) => {
      // ElMessage.error(`${err}`);
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryParams.code = undefined;
  queryParams.salesMan = undefined;
  queryParams.companyName = undefined;
  queryParams.status = undefined;
  queryParams.inputTime = undefined;

  handleQuery();
}

// 新增/修改/查看
function handleOpenDialog(row?: any, type?: string) {
  console.log(row.code, "row.code");

  infoDialog.type = type || "";
  infoDialog.visible = true;
  activeTabsName.value = "基础信息";
  if (type === "look") {
    //查看,不可编辑
    infoDialog.title = "查看客户信息";
    adCpQueryParams.parentCode = row.code;
    handleGetInfo();
    Object.assign(infoFormData, row);
  } else if (type == "update") {
    //修改
    infoDialog.title = "修改客户信息";
    adCpQueryParams.parentCode = row.code;
    handleGetInfo();
    //回显
    Object.assign(infoFormData, row);
  } else {
    infoDialog.type = "add";
    infoDialog.title = "新增客户信息";
  }
}

const adCpQueryParams = reactive<any>({
  pageNum: 1,
  pageSize: 10,
  parentCode: "",
});

//根据客户信息获取地址信息，联系人信息
function handleGetInfo() {
  cusInfoApi.getAddressPage(adCpQueryParams).then((res) => {
    addressList.value = res;
  });

  cusInfoApi.getContactPage(adCpQueryParams).then((res) => {
    contactList.value = res;
  });
}

//新增收货地址
function handleOpenAddressDialog(row?: any, type?: string) {
  console.log(row.address, "row");

  if (type === "edit") {
    addressDialog.title = "修改收货地址";
    //回显数据
    Object.assign(addressParams, row);
  } else {
    if (!adCpQueryParams.parentCode) {
      ElMessage.warning("请新增客户");
      return;
    }
    addressDialog.title = "新增收货地址";
  }
  addressDialog.visible = true;
}

//更新默认地址
function updateAddress(type: string, row?: any) {
  let query = {
    ...row,
  };
  query[type] = 1;
  query.parentCode = adCpQueryParams.parentCode;
  cusInfoApi
    .updateAddress(query)
    .then((res) => {
      ElMessage.success("操作成功");
    })
    .finally(() => {
      cusInfoApi.getAddressPage(adCpQueryParams).then((res) => {
        addressList.value = res;
      });
    });
}

//关闭地址弹窗
function handleCloseAddressDialog() {
  addressDialog.visible = false;
  addressRef.value.resetFields();

  clearAddressFormData();
}

//保存地址信息
function handleSaveAddress() {
  if (!adCpQueryParams.parentCode) {
    ElMessage.warning("请新增客户");
    return;
  }
  addressRef.value.validate((valid: any) => {
    if (!valid) return;
    addressParams.parentCode = adCpQueryParams.parentCode;
    if (addressParams.id) {
      cusInfoApi
        .updateAddress(addressParams)
        .then((res) => {
          ElMessage.success("操作成功");
        })
        .finally(() => {
          addressDialog.visible = false;
          addressParams.id = NaN;
          cusInfoApi.getAddressPage(adCpQueryParams).then((res) => {
            addressList.value = res;
          });
        });
    } else {
      cusInfoApi
        .addAddress(addressParams)
        .then((res) => {
          ElMessage.success("操作成功");
        })
        .finally(() => {
          addressDialog.visible = false;
          cusInfoApi.getAddressPage(adCpQueryParams).then((res) => {
            addressList.value = res;
          });
        });
    }
  });
}
//删除地址信息
function deleteAddress(id: number) {
  ElMessageBox.confirm("是否确认删除该地址信息？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      cusInfoApi.deleteAddressById(id).then((res) => {
        ElMessage.success("操作成功");
      });
    })
    .catch((err) => {
      ElMessage.info("已取消删除");
    })
    .finally(() => {
      cusInfoApi.getAddressPage(adCpQueryParams).then((res) => {
        addressList.value = res;
      });
    });
}

//打开联系人弹窗
function handleOpenContactDialog(contact?: any) {
  if (contact.id) {
    contactDialog.title = "修改联系人";
    Object.assign(contactPersonParams, contact);
  } else {
    contactDialog.title = "新增联系人";
    if (!adCpQueryParams.parentCode) {
      ElMessage.warning("请新增客户");
      return;
    }
  }
  contactDialog.visible = true;
}

//保存联系人
function handleSaveContact() {
  contactRef.value.validate((valid: any) => {
    if (!valid) return false;
    contactPersonParams.parentCode = adCpQueryParams.parentCode;
    if (contactPersonParams.id) {
      cusInfoApi
        .updateContact(contactPersonParams)
        .then((res) => {
          ElMessage.success("操作成功");
        })
        .finally(() => {
          contactDialog.visible = false;
          contactPersonParams.id = NaN;

          cusInfoApi.getContactPage(adCpQueryParams).then((res) => {
            contactList.value = res;
          });
        });
    } else {
      cusInfoApi
        .addContact(contactPersonParams)
        .then((res) => {
          ElMessage.success("操作成功");
        })
        .finally(() => {
          contactDialog.visible = false;
          cusInfoApi.getContactPage(adCpQueryParams).then((res) => {
            contactList.value = res;
          });
        });
    }
  });
}

//关闭联系人弹窗
function handleCloseContactDialog() {
  contactDialog.visible = false;
  contactRef.value.resetFields();
  //清空所有数据
  contactPersonParams.id = NaN;
  contactPersonParams.contactPerson = undefined;
  contactPersonParams.department = undefined;
  contactPersonParams.position = undefined;
  contactPersonParams.tel = undefined;
  contactPersonParams.email = undefined;
  contactPersonParams.remark = undefined;
}

//删除联系人
function deleteContact(id: number) {
  ElMessageBox.confirm("是否确认删除该联系人？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      cusInfoApi.deleteContactById(id).then((res) => {
        ElMessage.success("操作成功");
      });
    })
    .catch((err) => {
      ElMessage.warning(err.message || "已取消删除");
    })
    .finally(() => {
      cusInfoApi.getContactPage(adCpQueryParams).then((res) => {
        contactList.value = res;
      });
    });
}

// 清空客户表单数据
function clearFormData() {
  let data = {
    id: undefined, // 主键ID
    code: "", // 客户编号
    salesMan: "", // 跟进业务员
    companyName: "", // 中文名称
    otherName: "", // 英文名称
    nickName: "", // 简称
    contactPerson: "", // 主要联系人
    status: undefined, // 状态
    creditDeadline: "", // 授信截止时间
    website: "", // 公司网站
    accCode: "", // 对应财务系统编号
    accName: "", // 对应财务系统名称
    bankInfo: "", // 银行信息
    remark: "", // 备注
    fileInfoJson: "", // 附件信息，初始化为空数组
    clientType: "",
    businessLicenseNo: "",
    registerAddress: "",
  };
  Object.assign(infoFormData, data);
}

function clearAddressFormData() {
  let data = {
    id: undefined,
    addressName: "",
    address: "", // 收货地址
    contactPerson: "", // 联系人
    tel: "", // 联系电话
    email: "", // 邮箱
    isDefault: 0, // 是否默认地址
    isBilling: 0, // 是否账单地址
    isShipping: 0, // 是否发货地址
    remark: "", // 备注
  };
  Object.assign(addressParams, data);
}

// 关闭弹窗
function handleCloseDialog() {
  infoDialog.visible = false;

  infoFormRef.value?.clearValidate();
  infoFormRef.value?.resetFields();
  adCpQueryParams.parentCode = undefined;
  //清空地址和联系人数据
  addressList.value = [];
  contactList.value = [];
  submitButtonDisabled.value = false;
  clearFormData();
}

const submitButtonDisabled = ref(false);
//基础信息提交
function handleSubmitBase() {
  console.log(fileInfoJson.value, infoFormData.fileInfoJson, "fileInfoJson");
  //如果未上传附件，则校验不通过

  infoFormRef.value.validate((valid: boolean) => {
    if (JSON.parse(infoFormData.fileInfoJson || "[]").length === 0) {
      ElMessage.error("请上传附件");
      return;
    }
    if (!valid) {
      return;
    }

    if (infoDialog.type == "update") {
      cusInfoApi
        .update({ ...infoFormData })
        .then((data: any) => {
          ElMessage.success("提交成功");
          handleCloseDialog();
        })
        .catch((err) => {
          // ElMessage.error(`${err}`);
          // handleCloseDialog();
          handleResetQuery();
        })
        .finally(() => {
          handleQuery();
        });
    } else {
      cusInfoApi
        .add({ ...infoFormData })
        .then((data: any) => {
          ElMessage.success("提交成功");

          console.log(data, "data");
          adCpQueryParams.parentCode = data;
          // 添加联系人信息
          activeTabsName.value = "联系人信息";
          //禁用提交按钮

          submitButtonDisabled.value = true;
        })

        .catch((err) => {
          // ElMessage.error(`${err}`);
          // handleCloseDialog();
          handleResetQuery();
        })
        .finally(() => {
          handleQuery();
        });
    }
  });
  fileInfoJson.value = [];
}

/**
 * 删除客户信息
 * @param  id? number 客户信息id
 * @returns
 */

function handleDelete(id: number) {
  ElMessageBox.confirm("确认删除客户信息?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      cusInfoApi
        .deleteById(id)
        .then((data) => {
          ElMessage.success("删除成功");

          handleQuery();
        })
        .catch((err) => {
          // ElMessage.error(`${err}`);
          handleQuery();
        })
        .finally(() => {
          handleQuery();
          loading.value = false;
        });
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

function handleUpdateFileInfoJson(fileInfoJson: any) {
  let submitFileInfo = JSON.parse(infoFormData.fileInfoJson || "[]");
  submitFileInfo = [fileInfoJson[fileInfoJson.length - 1], ...submitFileInfo];
  infoFormData.fileInfoJson = JSON.stringify(submitFileInfo);
}

//下载附件
function downloadFile(name: string, filePath: string) {
  if (filePath) {
    FileAPI.downloadFile(filePath, name)
      .then((res: any) => {
        ElMessage.success("下载成功");
      })
      .catch((err: any) => {
        // ElMessage.error(`${err}`);
      });
  }
}
//删除附件
function deleteFile(index: number) {
  let submitFileInfo = JSON.parse(infoFormData.fileInfoJson || "[]");
  submitFileInfo.splice(index, 1);
  fileInfoJson.value.splice(index, 1);
  infoFormData.fileInfoJson = JSON.stringify(submitFileInfo);
}
//打开跟进弹窗
function handleOpenFollowDialog(row: any) {
  followDialog.visible = true;
  followDialog.title = "跟进记录";
  followParams.companyCode = row.code;
  followParams.salesMan = row.salesMan;
  followParams.followContactPerson = JSON.parse(sessionStorage.getItem("USER_INFO")!).name;
  followParams.contactType = JSON.parse(sessionStorage.getItem("USER_INFO")!).phone;
  //跟进日期默认为当前时间
  const now = new Date();
  followParams.followDate = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")} ${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}:${String(now.getSeconds()).padStart(2, "0")}`;
}

//保存跟进记录
function handleSaveFollow() {
  followRef.value?.validate((valid: boolean) => {
    if (!valid) {
      return;
    }
    salesApi
      .add({ ...followParams })
      .then((data) => {
        ElMessage.success("保存成功");
      })
      .catch((err) => {
        // ElMessage.error(`${err}`);
      })
      .finally(() => {
        handleQuery();
        followDialog.visible = false;
      });
  });
}
//关闭跟进弹窗
function handleCloseFollowDialog() {
  followDialog.visible = false;
  followRef.value?.clearValidate();
  followParams.followContactPerson = "";
  followParams.followDate = "";
  followParams.remark = "";
  followParams.contactType = "";
}

//打开跟进查看弹窗
function handleOpenFollowViewDialog(row: any) {
  console.log(row);

  let queryParams = {
    id: row.id,
    pageSize: 10,
    pageNum: 1,
    companyCode: row.code,
  };

  followViewDialog.visible = true;
  followViewDialog.title = "跟进记录";
  console.log(queryParams, "queryParams");

  salesApi
    .getList(queryParams)
    .then((data) => {
      console.log("data", data);

      followList.value = data.list;
    })
    .catch((err) => {
      // ElMessage.error(`${err}`);
    });
}

//删除跟进记录
function deleteRecord(row: any) {
  ElMessageBox.confirm("确认删除跟进记录?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      salesApi
        .delete(row.id)
        .then((data) => {
          ElMessage.success("删除成功");
        })
        .catch((err) => {
          // ElMessage.error(`${err}`);
        })
        .finally(() => {
          salesApi
            .getList({
              companyCode: row.companyCode,
            })
            .then((data) => {
              followList.value = data.list;
            })
            .catch((err) => {
              // ElMessage.error(`${err}`);
            });
          loading.value = false;
        });
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

//关闭跟进查看弹窗
function handleCloseFollowViewDialog() {
  followViewDialog.visible = false;
}

//查询所有客户和业务员信息

function handleAllCompanyQuery() {
  cusInfoApi.getPage({ pageNum: 1, pageSize: 999 }).then((data: any) => {
    allCompanyCode.value = data.records.map((item: any, idx: number) => ({
      value: item.code,
      label: `${item.code} - ${item.companyName}`,
    }));
  });
  UserAPI.getPage({ pageNum: 1, pageSize: 999, roleName: "salesMan" }).then((data) => {
    salesPersonList.value = data.list.map((item: any) => ({
      value: item.id,
      label: item.name,
    }));
    console.log(salesPersonList.value, "data");
  });
}

//授信类型
const creditTypeOptions = [
  { value: 0, label: "额度充值" },
  { value: 1, label: "购买产品" },
  { value: 2, label: "订单退货" },
  { value: 3, label: "取消退货" },
];
//根据value查出授信类型
const creditTypeLabel = (value: number) => {
  return creditTypeOptions.find((item) => item.value === value)?.label || "未知";
};

const dialogVisible = ref(false);
const rechargeDialogVisible = ref(false);
const creditAmount = ref(0);

const historyList = ref<creditAmountRecordPageVO[]>();

const rechargeForm = ref<{
  companyCode: string;
  amount?: number;
  remark?: string;
}>({
  companyCode: "",
  amount: undefined,
  remark: undefined,
});
//充值记录总条数
const creditTotal = ref(0);

//授信额度分页查询参数
const creditQueryParams = reactive<creditAmountRecordPageQuery>({
  pageNum: 1,
  pageSize: 10,
  companyCode: "",
  timeScopes: [],
});

//根据客户code查询流水记录
const handleCreditQuery = () => {
  rechargeForm.value.companyCode = creditQueryParams.companyCode;

  creditAmountRecordApi.getCreditAmountList(creditQueryParams).then((data: any) => {
    console.log(data, "data");
    historyList.value = data.list;
    creditTotal.value = data.total;
  });
};
//打开授信额度流水记录
const handleOpenCreditDialog = (row: any) => {
  dialogVisible.value = true;
  creditAmount.value = row.creditLimit;

  creditQueryParams.companyCode = row.code;
  // historyList.value = row.creditHistory;
  //查询流水记录
  handleCreditQuery();
};

//充值额度弹窗
const handleRecharge = () => {
  rechargeDialogVisible.value = true;
  rechargeForm.value.companyCode = creditQueryParams.companyCode;
  rechargeForm.value.amount = undefined;
  rechargeForm.value.remark = undefined;
};

//确认充值
const handleConfirmRecharge = (code: string) => {
  if (!rechargeForm.value.amount) {
    return;
  }

  creditAmountRecordApi
    .addCreditAmountRecord({
      companyCode: code,
      amount: rechargeForm.value.amount,
      remark: rechargeForm.value.remark || "手动充值",
      creditType: 0,
    })
    .then((data: any) => {
      ElMessage.success("充值成功");
      console.log(creditAmount.value, rechargeForm.value.amount, "充值成功");

      creditAmount.value += rechargeForm.value.amount || 0;
      handleCreditQuery();
      handleQuery();
    })
    .catch((err: any) => {
      // ElMessage.error(`${err}`);
    });

  rechargeDialogVisible.value = false;
  handleCreditQuery();
};

//关闭授信弹窗
const handleCloseCreditDialog = () => {
  creditQueryParams.pageNum = 1;
  creditQueryParams.pageSize = 10;

  creditQueryParams.timeScopes = [];
  rechargeDialogVisible.value = false;
};

onMounted(() => {
  handleQuery();
  handleAllCompanyQuery();
});
</script>

<style lang="scss" scoped></style>
